﻿package 
{
	import flash.events.EventDispatcher;
	import flash.net.Socket;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.IOErrorEvent;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.events.SecurityErrorEvent;

	public class IMConnection extends EventDispatcher
	{
		private var socket:Socket;
		private var host:String;
		private var port:int;
		public var myuserid:String;
		private var needautoreconnect:Boolean;
		private var heartTimer:Timer;
		
		public function IMConnection(remotehost:String,remoteport:int)
		{

			needautoreconnect=true;
			host=remotehost;
			port=remoteport;
			socket = new Socket();
			heartTimer=new Timer(30*1000);
			heartTimer.addEventListener(TimerEvent.TIMER,onHeartTimer);

			socket.addEventListener(Event.CONNECT,onSocketConnect);
			socket.addEventListener(Event.CLOSE,onSocketClose);
			socket.addEventListener(ProgressEvent.SOCKET_DATA,onSocketData);
			socket.addEventListener(IOErrorEvent.IO_ERROR,onSocketIOError);
			socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurityError);
		}
		
		public function onHeartTimer(evt:TimerEvent):void{
			Heart();
		}

		public function onSecurityError(evt:SecurityErrorEvent):void{
			trace("安全错误");
			if(needautoreconnect){
				try{
					socket.close();
				}catch(e:Error){
					
				}
				socket.connect(host,port);
			}
		}
		
		public function onSocketIOError(evt:IOErrorEvent):void
		{
			trace("IO错误" + evt.text);
			if(needautoreconnect){
				try{
					socket.close();
				}catch(e:Error){
					
				}
				socket.connect(host,port);
			}
		}

		public function onSocketConnect(evt:Event):void
		{
			trace("connected");
			dispatchEvent(new Event(Event.CONNECT));
			_Login(myuserid);
		}

		public function onSocketClose(evt:Event):void
		{
			trace("onSocketClose");
			heartTimer.stop();
			dispatchEvent(new Event(Event.CLOSE));
			if(needautoreconnect){
				socket.connect(host,port);
			}
		}

		public function onSocketData(evt:ProgressEvent):void
		{
			var evt1:IMEvent;
			if (socket.bytesAvailable > 0)
			{
				var retstr:String = socket.readMultiByte(socket.bytesAvailable,"UTF-8");
				var retarray:Array = retstr.split("\r\n");
				for (var j:int=0; j<retarray.length-1; j++)
				{
					var ret:String = retarray[j];
					var i:int = ret.search(" ");
					var cmd:String;
					var content:String = "";
					if (i == -1)
					{
						cmd = ret;
					}
					else
					{
						cmd = ret.substring(0,i);
						content = ret.substring(i + 1);
					}
					trace(ret);
					trace("cmd:[" + cmd + "]");
					trace("content:[" + content + "]");


					if (cmd == IMEvent.LOGINOK)
					{
						heartTimer.start();
						dispatchEvent(new IMEvent(IMEvent.LOGINOK));
					}
					else if (cmd==IMEvent.USERJOINROOM)
					{
						evt1 = new IMEvent(IMEvent.USERJOINROOM);
						evt1.peeruserid = content;
						dispatchEvent(evt1);
					}
					else if (cmd==IMEvent.USEREXITROOM)
					{
						evt1 = new IMEvent(IMEvent.USEREXITROOM);
						evt1.peeruserid = content;
						dispatchEvent(evt1);
					}
					else if (cmd==IMEvent.EXITROOMOK)
					{
						evt1 = new IMEvent(IMEvent.EXITROOMOK);
					}
					else if (cmd==IMEvent.ROOMUSERLIST)
					{
						evt1 = new IMEvent(IMEvent.ROOMUSERLIST);
						evt1.userlist = content.split(" ");
						trace(evt1.userlist.length);
						dispatchEvent(evt1);
					}
					else if (cmd==IMEvent.RECVMSG)
					{
						evt1 = new IMEvent(IMEvent.RECVMSG);
						i = content.search(" ");
						evt1.fromuserid = content.substring(0,i);
						content = content.substring(i + 1);
						i = content.search(" ");
						evt1.touserid = content.substring(0,i);
						evt1.msgconetnt = content.substring(i + 1);
						dispatchEvent(evt1);
					}
					else if (cmd==IMEvent.RECVROOMMSG)
					{
						evt1 = new IMEvent(IMEvent.RECVROOMMSG);
						i = content.search(" ");
						evt1.fromuserid = content.substring(0,i);
						content = content.substring(i + 1);
						i = content.search(" ");
						evt1.touserid = content.substring(0,i);
						content = content.substring(i + 1);
						i = content.search(" ");
						evt1.pub = content.substring(0,i) == "pub" ? true:false;
						evt1.msgconetnt = content.substring(i + 1);
						dispatchEvent(evt1);
					}
					else if (cmd==IMEvent.RECVSYSMSG)
					{
						evt1 = new IMEvent(IMEvent.RECVSYSMSG);
						evt1.content = content;
						dispatchEvent(evt1);
					}
					else if(cmd==IMEvent.SENDMSGOK){
						evt1=new IMEvent(IMEvent.SENDMSGOK);
						dispatchEvent(evt1);
					}else if(cmd==IMEvent.SENDMSGERROR){
						evt1=new IMEvent(IMEvent.SENDMSGERROR);
						evt1.content=content;
						dispatchEvent(evt1);
					}else if(cmd==IMEvent.BEKILLED){
						evt1=new IMEvent(IMEvent.BEKILLED);
						dispatchEvent(evt1);
						needautoreconnect=false;
						socket.close();
					}else
					{
						evt1 = new IMEvent(IMEvent.CMDERROR);
						evt1.content = content;
						dispatchEvent(evt1);
						
					}

				}

			}
		}

		public function Login(userid:String):void{
			myuserid=userid;
			socket.connect(host,port);
		}
		
		private function _Login(userid:String):void
		{
			if (socket.connected)
			{
				myuserid = userid;
				socket.writeMultiByte("login " + userid + "\r\n","UTF-8");
				socket.flush();
				trace("login " + userid);
			}
			else
			{
				var evt1:IMEvent;
				evt1 = new IMEvent(IMEvent.CMDERROR);
				evt1.content = "没有连接";
				dispatchEvent(evt1);
			}
		}

		public function Logout():void
		{
			needautoreconnect=false;
			if (socket.connected)
			{
				socket.writeMultiByte("LOGOUT " + "\r\n","UTF-8");
				socket.flush();
			}
			else
			{
				var evt1:IMEvent;
				evt1 = new IMEvent(IMEvent.CMDERROR);
				evt1.content = "没有连接";
				dispatchEvent(evt1);
			}
		}

		public function Heart():void
		{
			if (socket.connected)
			{
				trace("发送心跳包");
				socket.writeMultiByte("HEART " + "\r\n","UTF-8");
				socket.flush();
			}
			else
			{
				var evt1:IMEvent;
				evt1 = new IMEvent(IMEvent.CMDERROR);
				evt1.content = "没有连接";
				dispatchEvent(evt1);
			}
		}

		public function JoinRoom(roomid:String):void
		{
			if (socket.connected)
			{
				socket.writeMultiByte("joinroom " + roomid + "\r\n","UTF-8");
				socket.flush();
			}
			else
			{
				var evt1:IMEvent;
				evt1 = new IMEvent(IMEvent.CMDERROR);
				evt1.content = "没有连接";
				dispatchEvent(evt1);
			}
		}

		public function ExitRoom():void
		{
			if (socket.connected)
			{
				socket.writeMultiByte("exitroom " + "\r\n","UTF-8");
				socket.flush();
			}
			else
			{
				var evt1:IMEvent;
				evt1 = new IMEvent(IMEvent.CMDERROR);
				evt1.content = "没有连接";
				dispatchEvent(evt1);
			}
		}

		public function GetRoomUserList(roomid:String):void
		{
			if (socket.connected)
			{
				socket.writeMultiByte("roomuserlist " + roomid + "\r\n","UTF-8");
				socket.flush();
			}
			else
			{
				var evt1:IMEvent;
				evt1 = new IMEvent(IMEvent.CMDERROR);
				evt1.content = "没有连接";
				dispatchEvent(evt1);
			}
		}

		public function GetRoomUserCount(roomid:String):void
		{
			if (socket.connected)
			{
				socket.writeMultiByte("roomusercount " + roomid + "\r\n","UTF-8");
				socket.flush();
			}
			else
			{
				var evt1:IMEvent;
				evt1 = new IMEvent(IMEvent.CMDERROR);
				evt1.content = "没有连接";
				dispatchEvent(evt1);
			}
		}
		
		public function SendRoomMsg(peeruserid:String,pub:Boolean,content:String):void
		{
			var pubstr:String=pub?"pub":"nopub";
			if (socket.connected)
			{
				socket.writeMultiByte("sendmsg " + peeruserid + " " + pubstr + " " + content + "\r\n","UTF-8");
				socket.flush();
			}
			else
			{
				var evt1:IMEvent;
				evt1 = new IMEvent(IMEvent.CMDERROR);
				evt1.content = "没有连接";
				dispatchEvent(evt1);
			}
		}

		public function SendMsg(peeruserid:String,content:String):void
		{
			if (socket.connected)
			{
				socket.writeMultiByte("sendmsg " + peeruserid + " " + content + "\r\n","UTF-8");
				socket.flush();
			}
			else
			{
				var evt1:IMEvent;
				evt1 = new IMEvent(IMEvent.CMDERROR);
				evt1.content = "没有连接";
				dispatchEvent(evt1);
			}
		}

	}

}